package org.truenewx.tnxjee.repo.jdbc.flyway;

import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.MigrationInfo;
import org.flywaydb.core.api.MigrationInfoService;
import org.flywaydb.core.api.MigrationVersion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.flyway.FlywayMigrationStrategy;
import org.springframework.context.ApplicationContext;
import org.truenewx.tnxjee.core.message.MessageResolver;
import org.truenewx.tnxjee.core.util.SpringUtil;

/**
 * 默认迁移策略
 *
 * @author jianglei
 */
public class DefaultMigrationStrategy implements FlywayMigrationStrategy {

    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private MessageResolver messageResolver;

    @Override
    public void migrate(Flyway flyway) {
        if (check(flyway)) {
            // 在flyway执行之前，删除失败的增量脚本执行记录
            flyway.repair();
            flyway.migrate();
        }
    }

    protected boolean check(Flyway flyway) {
        MigrationInfoService migrationInfoService = flyway.info();
        MigrationInfo current = migrationInfoService.current();
        if (current != null) {
            MigrationVersion appliedVersion = current.getVersion();
            MigrationScanner scanner = new MigrationScanner(flyway.getConfiguration());
            String localVersion = scanner.getLatestVersion();
            // 已迁移版本比本地资源版本更新，则报错停止启动
            if (appliedVersion.isNewerThan(localVersion)) {
                String message = this.messageResolver.resolveMessage(
                        "info.tnxjee.repo.jpa.flyway.local_version_is_missing", localVersion, appliedVersion);
                SpringUtil.exit(this.applicationContext, message);
                return false;
            }
        }
        return true;
    }

}
